﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for OperatorModule
/// </summary>

public class OperatorModule  : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.PostAuthorizeRequest += new EventHandler(context_BeginRequest);
        //context.BeginRequest += new EventHandler(context_BeginRequest);
    }


    void context_BeginRequest(object sender, EventArgs e)
    {
        
        HttpApplication app = sender as HttpApplication;

        string IPAddress = app.Request.UserHostAddress.ToString();

        string UserName = app.User.Identity.Name.ToString();

        // Get key
        string key = app.Request.AppRelativeCurrentExecutionFilePath.ToLower();
        key = key.Substring(2).TrimEnd('/');

        // Ignore TCP web service
        if (key == "aslbtcp.asmx") return;

        // Get Params
        string Params = app.Request.QueryString.ToString();

        // Get the URL
        ASLBDataContext DC = new ASLBDataContext();

        string URL = "";
        DC.GetSession(key,UserName,IPAddress, Params, ref URL,false);

        if (URL == null)
        {
            // No redirect found, send ~/default.htm
            app.Response.StatusCode = 404;
            app.Response.StatusDescription = "Object Not Found";
            app.Response.WriteFile(app.Server.MapPath("~/default.htm"));
        }
        else
        {
            //Begin Response
            app.Response.StatusCode = 307;
            app.Response.StatusDescription = "Temporary Redirect";

            string ResponseBody = "<html><head><title>{2} {3}</title></head><body><h1>{2} {3}</h1><p>See <a href=\"{0}\">{0}</a></p></body></html>";

            app.Response.AppendHeader("Location", URL);
            app.Response.Output.Write(ResponseBody,
                URL,
                app.Request.Url,
                app.Response.StatusCode,
                app.Response.StatusDescription);

        }
        app.CompleteRequest();

    }
}

